#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>


typedef int (*process)(void *arg);

pid_t create_process(process entry, void *arg)
{
	int exit_value;
	pid_t pid;
	
	if(!entry)
		return -1;
	
	//创建子进程
	pid = fork();
	if(pid == 0)
	{
		//fork在子进程中返回0
		exit_value = entry(arg);
		exit(exit_value);
	}
	//fork在父进程中返回子进程的ID
	return pid;
}

int process1(void *arg)
{
	printf("%s", (char*)arg);
	sleep(1);
	//_exit是直接退出进程，不会属性标准IO流
	_exit(0);
}

int process2(void *arg)
{
	printf("%s", (char*)arg);
	sleep(2);
	//exit会进行刷新流、关闭流等操作，然后再退出进程
	exit(0);
}

int process3(void *arg)
{
	printf("%s", (char*)arg);
	printf("process3 PID=%d\r\n", getpid());
	printf("process3 PPID=%d\r\n", getppid());
	printf("process3 uid=%d\r\n", getuid());
    printf("process3 euid=%d\r\n", geteuid());
	printf("process3 gid=%d\r\n", getgid());
    printf("process3 egid=%d\r\n", getegid());
	sleep(3);
	return 0;
}

int main(int argv, char *argc[])
{
	int i;
	int state;
	pid_t temp;
	pid_t pid1,pid2,pid3;
	
	//同时创建的进程其执行的先后顺序不确定
	pid1 = create_process(process1, "process1;\r\n");
	printf("process1 PID=%d\r\n", pid1);
	
	pid2 = create_process(process2, "process2;\r\n");
	printf("process2 PID=%d\r\n", pid2);
	
	pid3 = create_process(process3, "process3;\r\n");
	printf("process3 PID=%d\r\n", pid3);
	
	for(i = 0; i < 3; i++)
	{
		//等待子进程退出
#if 0 
		temp = wait(&state);
#else
		temp = waitpid(-1, &state, 0);
#endif		
		printf("process %d exit\r\n", temp);
		//获取退出状态
		if(WIFEXITED(state)) 
			printf("exited, state=%d\r\n", WEXITSTATUS(state));
		else if(WIFSIGNALED(state))
			printf("killed by signal %d\r\n", WTERMSIG(state));
	}
	return 0;
}